﻿using System;
using System.Linq;
using NHibernate.Linq;
using nsadv.Statistic.Domain;
using nsadv.Statistic.Repository.NHibernate.Sessions;

namespace nsadv.Statistic.Repository.NHibernate
{
	public class Repository<TEntity> : IRepository<TEntity> where TEntity: Entity
	{
		protected readonly INHibernateSessionController SessionController;
		
		public Repository(INHibernateSessionController sessionController)
		{
			SessionController = sessionController;
		}

		public IQueryable<TEntity> All
		{
			get
			{
				return SessionController.Current.Linq<TEntity>(
					SessionController.Current.CreateCriteria<TEntity>().SetCacheable(true));
			}
		}

		public TEntity ById(string id)
		{
			return SessionController.Current.Get<TEntity>(id);
		}

		public void Add(TEntity entity)
		{
			try
			{
				SessionController.Current.Save(entity);
			}
			catch (Exception)
			{
				SessionController.Reset();
				throw;
			}
		}

		public void Update(TEntity entity)
		{
			try
			{
				SessionController.Current.Update(entity);
			}
			catch (Exception)
			{
				SessionController.Reset();
				throw;
			}
		}

		public void Delete(TEntity entity)
		{
			try
			{
				SessionController.Current.Delete(entity);
			}
			catch (Exception)
			{
				SessionController.Reset();
				throw;
			}
		}
	}
}
